import { getBaseUrl } from '@/services/urlconst';
import { getCompanyID, getPosIDs, getUserDepID, getUserID, requestFunComponFiex } from '@/utils';
import { message } from 'antd';
import { useRequest } from 'umi';

const baseUrl = getBaseUrl();

/**
 * 获取角色树
 * @param callback 接口回调
 * @returns
 */
const userTreeOfRoleService = (callback: (res: any) => void) => {
  const { run, loading, data } = useRequest(
    () => {
      let reqUrl = `${baseUrl}/userController/treeOfRole/${getUserID()}`;
      return requestFunComponFiex('GET', reqUrl, {});
    },
    {
      manual: true,
      onSuccess: callback,
    },
  );
  return {
    userTreeOfRoleRun: run,
    userTreeOfRoleLoading: loading,
    userTreeOfRoleData: data?.obj,
  };
};

/**
 * 获取用户详情
 * @param callback 接口回调
 * @returns
 */
const getUserByIDService = () => {
  const { run, loading, data } = useRequest(
    (params: Record<string, any>) => {
      let reqUrl = `${baseUrl}/userController/getUserByID/${params?.userID}`;
      return requestFunComponFiex('GET', reqUrl, {});
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (!(res && res?.msgFlag)) {
          message.error(res?.msg);
        }
      },
    },
  );
  return {
    getUserByIDRun: run,
    getUserByIDLoading: loading,
    getUserByIDInfo: data?.obj,
  };
};

/**
 * 给用户设置角色
 * @param callback 接口回调
 * @returns
 */
const grantUserRoleService = (callback: (res: any) => void) => {
  const { run, loading } = useRequest(
    (params: any) => {
      const bodyParams: Record<string, any> = {
        ...params,
        modifyerID: getUserID(),
        modifyPositionID: getPosIDs(),
        modifyDepartmentID: getUserDepID(),
        modifyCompanyID: getCompanyID(),
      };
      let reqUrl = `${baseUrl}/userController/grant`;
      return requestFunComponFiex('PUT', reqUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess: callback,
    },
  );
  return {
    grantUserRoleRun: run,
    grantUserRoleLoading: loading,
  };
};

export { userTreeOfRoleService, getUserByIDService, grantUserRoleService };
